namespace TomatoBreak.Infrastructure
{
    using System;
    using System.Globalization;
    using System.Linq;
    using System.Web.Mvc;

    public class DateBinder : IModelBinder
    {
        private static readonly string[] dateFormats = new[] { "yyyy-MM-dd", "yyyy/MM/dd" };

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException("bindingContext");
            }

            var result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            if (result == null)
            {
                return null;
            }

            var parsedDate = Clock.UtcNow();

            if (dateFormats.Any(dateFormat => TryParseDate(result.AttemptedValue, dateFormat, out parsedDate)))
            {
                return parsedDate;
            }

            return null;
        }

        private static bool TryParseDate(string value, string format, out DateTime result)
        {
            return DateTime.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out result);
        }
    }
}